package com.chunxuan.langquan.ui.activity;

import android.animation.Animator;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Message;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.VideoView;

import androidx.appcompat.app.AlertDialog;
import androidx.core.widget.ContentLoadingProgressBar;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chunxuan.langquan.MainActivity;
import com.chunxuan.langquan.R;
import com.chunxuan.langquan.base.Base2Activity;
import com.chunxuan.langquan.base.BaseResult2;
import com.chunxuan.langquan.base.Global;
import com.chunxuan.langquan.dao.bean.CourseDetail;
import com.chunxuan.langquan.dao.http.APIRetrofit2;
import com.chunxuan.langquan.support.util.AlertUtil;
import com.chunxuan.langquan.support.util.GlideUtil;
import com.chunxuan.langquan.support.util.Logg;
import com.chunxuan.langquan.support.util.TimeUtil;
import com.chunxuan.langquan.support.view.MyAnimatorListener;
import com.m7.imkfsdk.KfStartHelper;
import com.m7.imkfsdk.utils.permission.PermissionConstants;
import com.m7.imkfsdk.utils.permission.PermissionXUtil;
import com.m7.imkfsdk.utils.permission.callback.OnRequestCallback;
import com.moor.imkf.requesturl.RequestUrl;
import com.ruitu.arad.api.RxUtil;
import com.ruitu.arad.base.base_list.ListBaseAdapter;
import com.ruitu.arad.base.base_list.SuperViewHolder;
import com.ruitu.arad.util.HandlerUtil;
import com.ruitu.arad.util.ScreenUtils;
import com.ruitu.arad.util.SizeUtils;
import com.ruitu.arad.util.ToastUtils;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

public class CourseDetailActivity extends Base2Activity implements HandlerUtil.OnReceiveMessageListener {
    private VideoView vv_video;
    private RelativeLayout rl_player, rl_area_code;// 播放器的布局
    private SeekBar seek_bar;// 进度条
    private TextView tv_time, tv_total_time;// 播放时间,总时间
    private ImageView iv_play, iv_play_vv, iv_pause, iv_full_screen, iv_full_screen_quit;// 播放 播放2 暂停 全屏 退出全屏
    private LinearLayout rl_progress;// 缓冲布局
    private ContentLoadingProgressBar progress_bar;// 缓冲进度条
    private TextView tv_hint, tv_title;// 提示文字,标题
    private TextView tv_login, tv_buy;// 登录, 购买
    private LinearLayout rl_content;// 播放器下面的内容部分
    private RelativeLayout rl_title, rl_control;// 标题,控制按钮
    private TextView tv_course_name, tv_desc, tv_teacher_name;// 课程名,课程信息,老师名
    private ImageView iv_teacher_header;// 老师头像
    private TextView tv_name, tv_date, tv_comment_content;// 评论模块的用户名,日期,内容
    private ImageView iv_comment_header;// 评论的用户头像
    private RecyclerView rcv_reco_list;// 推荐课程列表
    private EditText et_comment;
    private TextView tv_comment;//
    private TextView tv_send;// 发送
    private ImageView iv_cust, iv_add;// 客服,添加
    private RelativeLayout rl_header, rl_bottom;
    private ImageView iv_back, iv_back_vv;// 返回
    private LinearLayout ll_teacher_info;// 教师信息
    private RecyclerView rcv_labels;// 学员评价标签
    private WebView webview;
    private TextView tv_check_all_comment;
    private TextView tv_area_code;// 视频上显示的区域代码
    private ImageView iv_course_image;// 课程图片

    private String grade_category_id, subject_category_id, class_category_id, course_id;// 传过来的课程id
    private CourseDetail detail;// 请求得到的课程详情

    private RecoListAdapter recoAdapter;// 推荐课程adapter
    private LabeListAdapter labelAdapter;// 学员评价标签
    private List<LabelData> labelDataList = new ArrayList<>();// 评论标签列表
    private List<String> labelList = new ArrayList<>();// 评论标签列表

    private String videoUrl = "";

    private static final int TIME = 3;
    private int HIDE_TIME = TIME;// 隐藏控制按钮倒计时
    private int currStayTime = 0;// 记录当前视频播放以后经过的时间,用于五分钟以后弹窗提示用户买视频
    private HandlerUtil.HandlerHolder handler;

    private boolean isFirstPlay = true;
    public final static String CSS_STYLE = "<style>* p {color:#72ECFB;}</style>";

    @Override
    protected int getLayoutRes() {
        return R.layout.activity_course_detail;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        // 隐藏标题栏
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        // 隐藏状态栏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

        super.onCreate(savedInstanceState);
        vv_video = findViewById(R.id.vv_video);
        rl_player = findViewById(R.id.rl_player);
        rl_area_code = findViewById(R.id.rl_area_code);
        seek_bar = findViewById(R.id.seek_bar);
        tv_time = findViewById(R.id.tv_time);
        tv_total_time = findViewById(R.id.tv_total_time);
        iv_play = findViewById(R.id.iv_play);
        iv_play_vv = findViewById(R.id.iv_play_vv);
        iv_pause = findViewById(R.id.iv_pause);
        iv_full_screen = findViewById(R.id.iv_full_screen);
        iv_full_screen_quit = findViewById(R.id.iv_full_screen_quit);
        rl_progress = findViewById(R.id.rl_progress);
        progress_bar = findViewById(R.id.progress_bar);
        tv_hint = findViewById(R.id.tv_hint);
        tv_title = findViewById(R.id.tv_title);
        tv_login = findViewById(R.id.tv_login);
        tv_buy = findViewById(R.id.tv_buy);
        rl_content = findViewById(R.id.rl_content);
        rl_title = findViewById(R.id.rl_title);
        rl_control = findViewById(R.id.rl_control);
        tv_course_name = findViewById(R.id.tv_course_name);
        tv_desc = findViewById(R.id.tv_desc);
        tv_teacher_name = findViewById(R.id.tv_teacher_name);
        iv_teacher_header = findViewById(R.id.iv_teacher_header);
        tv_name = findViewById(R.id.tv_name);
        tv_date = findViewById(R.id.tv_date);
        tv_comment_content = findViewById(R.id.tv_comment_content);
        iv_comment_header = findViewById(R.id.iv_comment_header);
        rcv_reco_list = findViewById(R.id.rcv_reco_list);
        tv_comment = findViewById(R.id.tv_comment);
        iv_cust = findViewById(R.id.iv_cust);
        if(Global.IS_SHOW==0){
            iv_cust.setVisibility(View.INVISIBLE);
        }else if(Global.IS_SHOW==1){
            iv_cust.setVisibility(View.VISIBLE);
        }
        iv_add = findViewById(R.id.iv_add);
        rl_header = findViewById(R.id.rl_header);
        rl_bottom = findViewById(R.id.rl_bottom);
        iv_back = findViewById(R.id.iv_back);
        iv_back_vv = findViewById(R.id.iv_back_vv);
        ll_teacher_info = findViewById(R.id.ll_teacher_info);
        rcv_labels = findViewById(R.id.rcv_labels);
        webview = findViewById(R.id.webview);
        tv_check_all_comment = findViewById(R.id.tv_check_all_comment);
        tv_area_code = findViewById(R.id.tv_area_code);
        iv_course_image = findViewById(R.id.iv_course_image);

        grade_category_id = getIntent().getStringExtra("grade_category_id");
        subject_category_id = getIntent().getStringExtra("subject_category_id");
        class_category_id = getIntent().getStringExtra("class_category_id");
        course_id = getIntent().getStringExtra("course_id");

        setHeadTitle("课程详情");

        handler = new HandlerUtil.HandlerHolder(this);
        handler.sendEmptyMessage(21031051);

        recoAdapter = new RecoListAdapter(this);

        alert = new AlertDialog.Builder(this, R.style.Dialog_FS).create();
        alert2 = new AlertDialog.Builder(this, R.style.Dialog_FS).create();

        setListeners();

        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) rl_player.getLayoutParams();
        params.width = ScreenUtils.getScreenWidth();
        params.height = params.width * 9 / 16;
        rl_player.setLayoutParams(params);
        rl_area_code.setLayoutParams(params);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//默认先给个竖屏
        setVideoHint("视频信息加载中");

        labelAdapter = new LabeListAdapter(this);
        GridLayoutManager manager = new GridLayoutManager(this, 4);
        rcv_labels.setLayoutManager(manager);
        rcv_labels.setAdapter(labelAdapter);

        reqCourseDetail();
        showProgress();
    }

    private Disposable reqSaveRecord() {
        return APIRetrofit2.getDefault().reqSaveRecord(Global.HEADER, course_id)
                .compose(RxUtil.subIoObMain())
                .subscribe(new Consumer<BaseResult2>() {
                    @Override
                    public void accept(BaseResult2 baseResult2) throws Exception {
                        if (baseResult2.isSuccess()) {
                            Logg.i("保存播放记录成功");
                        } else {
                            Logg.i(baseResult2.getMsg());
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        throwable.printStackTrace();
                    }
                });
    }

    private Disposable reqCourseDetail() {
        return APIRetrofit2.getDefault().reqCourseDetail(Global.HEADER, course_id)
                .compose(RxUtil.<BaseResult2<CourseDetail>>subIoObMain())
                .subscribe(new Consumer<BaseResult2<CourseDetail>>() {
                    @Override
                    public void accept(BaseResult2<CourseDetail> result2) throws Exception {
                        hideProgress();
                        reqSaveRecord();
                        reqLabelList();
                        currStayTime = 0;// 重置五分钟计时器
                        if (result2.isSuccess()) {
                            detail = result2.getData();
                            setData2View();
                        } else {
                            ToastUtils.showShort(result2.getMsg());
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                        ToastUtils.showShort("获取课程详情失败");
                    }
                });
    }

    private Disposable reqPublishComment(String content, String tags) {
        return APIRetrofit2.getDefault().reqPublishComment(Global.HEADER, course_id, content, tags)
                .compose(RxUtil.subIoObMain())
                .subscribe(new Consumer<BaseResult2>() {
                    @Override
                    public void accept(BaseResult2 baseResult2) throws Exception {
                        hideProgress();
                        ToastUtils.showShort(baseResult2.getMsg());
                        if (baseResult2.isSuccess()) {
                            alert2.dismiss();
                        } else {

                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        throwable.printStackTrace();
                        hideProgress();
                    }
                });
    }

    // 获取标签列表
    private Disposable reqLabelList() {
        labelDataList.clear();
        labelList.clear();
        return APIRetrofit2.getDefault().reqLabelList(Global.HEADER, "param")
                .compose(RxUtil.subIoObMain())
                .subscribe(new Consumer<BaseResult2<List<String>>>() {
                    @Override
                    public void accept(BaseResult2<List<String>> listResult2) throws Exception {
                        if (listResult2.isSuccess()) {
                            try {
                                labelList = listResult2.getData();
                                for (int i = 0; i < labelList.size(); i++) {
                                    LabelData data = new LabelData();
                                    data.setLabel(labelList.get(i));
                                    data.setSelect(false);
                                    labelDataList.add(data);
                                }
                                labelAdapter.setDataList(labelDataList);
                                Logg.i("labelDataList.size() = " + labelDataList.size());
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        } else {

                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        throwable.printStackTrace();
                    }
                });
    }

    // 设置课程数据到页面
    private void setData2View() {
        if (null != detail) {
            CourseDetail.CourseInfo courseInfo = detail.getCourse_info();
            if (null != courseInfo) {
                tv_course_name.setText(courseInfo.getTitle());
                tv_desc.setText(courseInfo.getSummary());
                GlideUtil.loadImg(courseInfo.getKecheng_image(), iv_course_image);
                initWebview(courseInfo.getContent());
                tv_area_code.setText("地区编码：" + courseInfo.getCourse_code());
                startMarquee();// 开始跑马灯效果

                tv_title.setText(courseInfo.getTitle());
                videoUrl = courseInfo.getVideo_file();

            } else {
                tv_course_name.setText("暂无课程名称");
                tv_desc.setText("暂无课程信息");
            }

            CourseDetail.TeacherInfo teacherInfo = detail.getTeacher_info();
            if (null != teacherInfo) {
                tv_teacher_name.setText(teacherInfo.getName());
                GlideUtil.loadImg(teacherInfo.getTeacheravatar(), iv_teacher_header);
            } else {
                tv_teacher_name.setText("暂无老师姓名");
            }

            CourseDetail.CommentInfo commentInfo = detail.getComment_info();
            if (null != commentInfo) {
                tv_name.setText(commentInfo.getUser_name());
                tv_date.setText(commentInfo.getComment_time());
                tv_comment_content.setText(commentInfo.getContent());
                //以下一行代码，控制是否展示用户评价
//                tv_comment_content.setVisibility(View.INVISIBLE);




//                GlideUtil.loadImg(commentInfo.getUser_name(),iv_comment_header);

//                try {
//                    String labels = commentInfo.getTags();
//                    if (!TextUtils.isEmpty(labels)) {
//                        String[] labelArr = labels.split(",");
//                        labelList = Arrays.asList(labelArr);
//                        for (int i = 0; i < labelList.size(); i++) {
//                            LabelData data = new LabelData();
//                            data.setLabel(labelList.get(i));
//                            data.setSelect(false);
//                            labelDataList.add(data);
//                        }
//                    }
//                    labelAdapter.setDataList(labelDataList);
//                    Logg.i("labelDataList.size() = " + labelDataList.size());
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }

            } else {
                tv_name.setText("暂无用户");
                tv_date.setText("");
                tv_comment_content.setText("暂无评价");
            }

            List<CourseDetail.RecommendInfo> recommendInfoList = detail.getRecommend_info();
            if (!isDataEmpty(recommendInfoList)) {
                LinearLayoutManager manager = new LinearLayoutManager(this);
                manager.setOrientation(RecyclerView.VERTICAL);
                rcv_reco_list.setLayoutManager(manager);
                rcv_reco_list.setAdapter(recoAdapter);
                recoAdapter.setDataList(recommendInfoList);
            } else {

            }
        }
    }

    private int containerX = 0;
    private int containerY = 0;
    private int DIRECTION = 1;// 地区码运动方向 1 右 2 下 3 左 4 上
    private int STEP = 5;// 地区码移动的步进大小
    private int INTERVAL = 33;// 地区码移动的时间间隔

    // 开始跑马灯效果
    private void startMarquee() {
        handler.removeMessages(21031551);

        DIRECTION = 1;
        containerX = ScreenUtils.getScreenWidth() - SizeUtils.dp2px(10);
        containerY = rl_player.getMeasuredHeight() - SizeUtils.dp2px(10);

        handler.sendEmptyMessageDelayed(21031551, INTERVAL);
    }

    private void setListeners() {
        setOnClickListener(iv_play, iv_play_vv, iv_pause, iv_full_screen, iv_full_screen_quit, tv_login
                , tv_buy, iv_cust, iv_back, iv_back_vv, ll_teacher_info, tv_check_all_comment, tv_comment);

//        vv_video.setOnTouchListener(new View.OnTouchListener() {
//            @Override
//            public boolean onTouch(View v, MotionEvent event) {
//                showCtrlAndResetTime();
//                return false;
//            }
//        });

        rl_player.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                showCtrlAndResetTime();
                return false;
            }
        });

//        et_comment.setOnFocusChangeListener(new View.OnFocusChangeListener() {
//            @Override
//            public void onFocusChange(View v, boolean hasFocus) {
//                showSendBtn(hasFocus);
//            }
//        });
    }

    /**
     * 初始化SDK
     */
    private void initSdk() {
        // 第一步:初始化help
        final KfStartHelper helper = new KfStartHelper(this);

        RequestUrl.setRequestBasic(RequestUrl.Tencent_REQUEST);

        String userName = "朗权通学用户";
        String uid = "test_uid";

        try {
            userName = Global.USER_INFO.getNickname();
            uid = "langquan_"+Global.USER_INFO.getUser_id();
        } catch (Exception e) {
            e.printStackTrace();
        }

        /*
          第三步:设置参数
          初始化sdk方法，必须先调用该方法进行初始化后才能使用IM相关功能
          @param accessId       接入id（需后台配置获取）
          @param userName       用户名
          @param userId         用户id
         */
        helper.initSdkChat("8e8e12a0-7cc1-11eb-b055-5fc538d90331", userName, uid);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        if (v == iv_back || v == iv_back_vv) {
            onBackPressed();
        }
        if (v == tv_comment) {// 点击请输入内容,弹出评价对话框
            showDialog2();
        }
        if (v == iv_cust) {// 客服
            //初始化SDK
            PermissionXUtil.checkPermission(this, new OnRequestCallback() {
                @Override
                public void requestSuccess() {
                    initSdk();
                }
            }, PermissionConstants.STORE, PermissionConstants.PHONE_STATE);
        }
        if (v == tv_send) {
            String content = et_comment.getText().toString().trim();
            if (TextUtils.isEmpty(content)) {
                ToastUtils.showShort("请输入内容");
                return;
            }
//            et_comment.clearFocus();
//            KeyboardUtils.hideSoftInput(et_comment);
//            ToastUtils.showShort(comment);
//            et_comment.setText("");

            String tags = "";// 用户评价时选择的标签
            StringBuilder sb = new StringBuilder(tags);
            for (int i = 0; i < labelDataList.size(); i++) {
                if (labelDataList.get(i).isSelect) {
                    sb.append(labelDataList.get(i).getLabel());
                    sb.append(",");
                }
            }
            tags = sb.toString();
            if (!TextUtils.isEmpty(tags)) {
                tags = tags.substring(0, tags.lastIndexOf(","));
            }
            Logg.i("tags = " + tags);
            hideProgress();
            reqPublishComment(content, tags);
            showProgress();
        }
        if (v == ll_teacher_info) {// 教师信息
            if (null != detail && null != detail.getTeacher_info()) {
                Bundle bundle = new Bundle();
                bundle.putString("teacher_id", detail.getTeacher_info().getId());
                startActivity(CourseTeacherInfoActivity.class, bundle);
            } else {
                ToastUtils.showShort("信息加载中...");
            }
        }
        if (v == tv_check_all_comment) {// 查看全部评价
            Bundle bundle = new Bundle();
            bundle.putString("course_id", course_id);
            bundle.putSerializable("labelList", (Serializable) labelList);
            startActivity(CourseTeacherCommentAllActivity.class, bundle);
        }
        if (v == iv_play_vv) {
            if (null == detail || null == detail.getCourse_info() || TextUtils.isEmpty(detail.getCourse_info().getVideo_file())) {
                ToastUtils.showShortSafe("视频详情加载中");
                return;
            }
            if (isFirstPlay) {
                CourseDetail.CourseInfo courseInfo = detail.getCourse_info();
                tv_title.setText(courseInfo.getTitle());
                videoUrl = courseInfo.getVideo_file();
                if (!TextUtils.isEmpty(videoUrl)) {
                    setUrl();
                    setPlayListener();// 设置播放监听

                    progress_bar.setVisibility(View.VISIBLE);
                    tv_login.setVisibility(View.GONE);
                    tv_buy.setVisibility(View.GONE);
                    setVideoHint("视频正在缓冲");
                } else {
                    if (TextUtils.equals("0", courseInfo.getStatus())) {// 0 未购买 1 已购买 2 未登录 3 免费
                        progress_bar.setVisibility(View.GONE);
                        tv_login.setVisibility(View.GONE);
                        tv_buy.setVisibility(View.VISIBLE);
                        setVideoHint("付费视频,购买才能观看");
                    } else if (TextUtils.equals("2", courseInfo.getStatus())) {
                        progress_bar.setVisibility(View.GONE);
                        tv_login.setVisibility(View.VISIBLE);
                        tv_buy.setVisibility(View.GONE);
                        setVideoHint("尚未登录,登录才能观看");
                    } else {

                    }
                }

                isFirstPlay = false;
            } else {
                start();
            }
            showCtrlAndResetTime();
        }
        if (v == iv_play) {// 播放
            if (null == detail || null == detail.getCourse_info() || TextUtils.isEmpty(detail.getCourse_info().getVideo_file())) {
                ToastUtils.showShortSafe("视频详情加载中");
                return;
            }
            start();
            showCtrlAndResetTime();
        }
        if (v == iv_pause) {// 暂停
            iv_play.setVisibility(View.VISIBLE);
            iv_play_vv.setVisibility(View.VISIBLE);
            iv_pause.setVisibility(View.GONE);
            pause();
            showCtrlAndResetTime();
        }
//        if (v == tv_3) {// 停止
//            stop();
//        }
//        if (v == tv_4) {// 试看
//            startOnlyHead();
//        }
        if (v == iv_full_screen) {// 全屏
            if (!isPrepared) {
                ToastUtils.showShortSafe("视频加载中...");
                return;
            }
            fullScreen();
            showCtrlAndResetTime();
        }
        if (v == iv_full_screen_quit) {
            if (!isPrepared) {
                ToastUtils.showShortSafe("视频加载中...");
                return;
            }
            fullScreen();
            showCtrlAndResetTime();
        }
        if (v == tv_login) {
//            CommonUtils.isLoginToActivity(this);
        }
        if (v == tv_buy) {
            ToastUtils.showShortSafe("购买视频");
        }
    }

    private void showSendBtn(boolean isShow) {
        if (isShow) {
            tv_send.setVisibility(View.VISIBLE);
            iv_cust.setVisibility(View.GONE);
            iv_add.setVisibility(View.GONE);
        } else {
            tv_send.setVisibility(View.GONE);
            iv_cust.setVisibility(View.VISIBLE);
            iv_add.setVisibility(View.VISIBLE);
        }
    }

    private void setFullIconState(boolean isFull) {
        if (isFull) {
            iv_full_screen.setVisibility(View.GONE);
            iv_full_screen_quit.setVisibility(View.VISIBLE);
        } else {
            iv_full_screen.setVisibility(View.VISIBLE);
            iv_full_screen_quit.setVisibility(View.GONE);
        }
    }

    private boolean isPlayHead = false;// 是否是试看
    private Integer sMillis = 10000;// 试看的时间毫秒值
    private boolean isPrepared = false;
    private int currVideoWidth = 0;//当前视频宽
    private int currVideoHeight = 0;//当前视频高

    private void setUrl() {
        if (TextUtils.isEmpty(videoUrl)) {
            setVideoHint("视频信息有误");
            ToastUtils.showShortSafe("视频信息有误");
            return;
        }
        vv_video.setVideoURI(Uri.parse(videoUrl));// 装载播放地址
    }

    private void start() {
        if (isPrepared) {
            if (isPlayHead && vv_video.getCurrentPosition() >= sMillis) {// 是试看
                ToastUtils.showShortSafe("试看" + sMillis + "毫秒结束");
            } else {
                vv_video.start();
                iv_play.setVisibility(View.GONE);
                iv_play_vv.setVisibility(View.GONE);
                iv_pause.setVisibility(View.VISIBLE);
                handler.sendEmptyMessage(2020031051);
            }
        } else {
            ToastUtils.showShortSafe("视频加载中,请稍候重试");
        }

        handler.removeMessages(2019102551);
        handler.sendEmptyMessage(2019102551);
    }

    private void pause() {
        vv_video.pause();
    }

    public void stop() {
        vv_video.setBackgroundColor(Color.parseColor("#000000"));
        vv_video.stopPlayback();
        vv_video.setVideoURI(null);
        isPrepared = false;

        rl_progress.setVisibility(View.VISIBLE);
        progress_bar.setVisibility(View.VISIBLE);
        tv_login.setVisibility(View.GONE);
        tv_buy.setVisibility(View.GONE);
        setVideoHint("视频信息加载中");
    }

    private void startOnlyHead() {
        isPlayHead = !isPlayHead;
        if (isPlayHead) {
            ToastUtils.showShortSafe("已开启试看");
//            tv_4.setText("关闭试看");
        } else {
            ToastUtils.showShortSafe("已关闭试看");
//            tv_4.setText("试看");
        }

        handler.removeMessages(2019102551);
        handler.sendEmptyMessage(2019102551);
    }

    @SuppressWarnings(value = "all")
    private void fullScreen() {
        //判断当前屏幕方向
        if (getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
            this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            setFullIconState(false);
        } else {
            this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
            setFullIconState(true);
        }
    }

    @SuppressWarnings(value = "all")
    @Override
    public void onBackPressed() {//点击返回的时候先切换竖屏
        if (getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            setFullIconState(false);
        } else {
            super.onBackPressed();
        }
    }

    @Override//横竖屏切换的时候执行
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        setVideoViewSize(isScreenPortrait());
        rl_player.postDelayed(new Runnable() {
            @Override
            public void run() {
                startMarquee();// 开始跑马灯效果
            }
        }, 50);
        if (getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
            rl_content.setVisibility(View.GONE);
            rl_header.setVisibility(View.GONE);
            rl_bottom.setVisibility(View.GONE);
            iv_back.setVisibility(View.VISIBLE);
        } else {
            rl_content.setVisibility(View.VISIBLE);
            rl_header.setVisibility(View.VISIBLE);
            rl_bottom.setVisibility(View.VISIBLE);
            iv_back.setVisibility(View.INVISIBLE);
        }
    }

    private void setVideoViewSize(boolean isPortrait) {//设置VideoView的尺寸
        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) rl_player.getLayoutParams();
        RelativeLayout.LayoutParams params2 = (RelativeLayout.LayoutParams) vv_video.getLayoutParams();
        if (isPortrait) {
            params.width = ScreenUtils.getScreenWidth();
            params.height = params.width * 9 / 16;

            params2.height = params.height;
            params2.width = currVideoWidth * params2.height / currVideoHeight;
            params2.addRule(RelativeLayout.CENTER_IN_PARENT);

        } else {
            params.width = ScreenUtils.getScreenWidth();
            params.height = ScreenUtils.getScreenHeight();

            params2.height = ScreenUtils.getScreenHeight();
            params2.width = currVideoWidth * params2.height / currVideoHeight;
            params2.addRule(RelativeLayout.CENTER_IN_PARENT);

        }
        rl_player.setLayoutParams(params);
        rl_area_code.setLayoutParams(params);
        vv_video.setLayoutParams(params2);
    }

    private boolean isScreenPortrait() {//屏幕是否是竖屏
        return getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
    }

    private void setPlayListener() {
        handler.removeMessages(2019102551);
        vv_video.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                handler.sendEmptyMessage(21031351);// 记录五分钟后不定时弹窗
                isPrepared = true;
                start();
                iv_course_image.setVisibility(View.GONE);// 隐藏课程图片

                seek_bar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                    @Override
                    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                        if (fromUser) {
                            if (isPlayHead && progress >= sMillis) {// 是试看
                                ToastUtils.showShortSafe("该视频只允许试看" + sMillis + "毫秒");
                                seekBar.setProgress(sMillis);
                                pause();
                            }
                            vv_video.seekTo(seekBar.getProgress());
                            tv_time.setText(TimeUtil.getMinAndSec(vv_video.getCurrentPosition()));
                            showCtrlAndResetTime();
                        }
                    }

                    @Override
                    public void onStartTrackingTouch(SeekBar seekBar) {
                    }

                    @Override
                    public void onStopTrackingTouch(SeekBar seekBar) {
                    }
                });
            }
        });
        vv_video.setOnInfoListener(new MediaPlayer.OnInfoListener() {
            @Override
            public boolean onInfo(MediaPlayer mp, int what, int extra) {
                rl_progress.setVisibility(View.GONE);
                vv_video.setBackgroundColor(Color.parseColor("#00000000"));
                showCtrlAndResetTime();

                seek_bar.setMax(vv_video.getDuration());
                tv_total_time.setText(TimeUtil.getMinAndSec(vv_video.getDuration()));
                handler.sendEmptyMessage(2019102551);

                currVideoWidth = mp.getVideoWidth();
                currVideoHeight = mp.getVideoHeight();
                setVideoViewSize(isScreenPortrait());
                return false;
            }
        });
        vv_video.setOnErrorListener(new MediaPlayer.OnErrorListener() {
            @Override
            public boolean onError(MediaPlayer mp, int what, int extra) {
                ToastUtils.showShort("视频路径错误,请检查视频路径后重试");
                vv_video.stopPlayback();
                return true;
            }
        });
    }

    @Override
    public void handlerMessage(Message msg) {
        if (msg.what == 2019102551) {// 视频播放
            if (isPlayHead) {// 试看
                handler.removeMessages(2019102551);
                if (vv_video.getCurrentPosition() >= sMillis) {
                    vv_video.seekTo(sMillis);
                    seek_bar.setProgress(vv_video.getCurrentPosition());
                    pause();
                    ToastUtils.showShortSafe("试看" + sMillis + "毫秒结束");
                } else {
                    handler.sendEmptyMessageDelayed(2019102551, 200);
                }
            } else {
                handler.removeMessages(2019102551);
                handler.sendEmptyMessageDelayed(2019102551, 200);
            }

            seek_bar.setProgress(vv_video.getCurrentPosition());
            tv_time.setText(TimeUtil.getMinAndSec(vv_video.getCurrentPosition()));
        }
        if (msg.what == 2020031051) {// 隐藏控制按钮倒计时
            handler.removeMessages(2020031051);
            if (HIDE_TIME <= 0) {
                showOrHideCtrl(false);
            } else {
                HIDE_TIME--;
                handler.sendEmptyMessageDelayed(2020031051, 1000);
            }
        }
        if (msg.what == 21031051) {// 每秒收到一次信息,用于显示弹窗
            handler.removeMessages(21031051);
            if (null != detail && null != detail.getCourse_info()// 数据请求完成
                    && isPrepared && !alert.isShowing()) {// 视频已经准备好了,当前未显示弹窗
                long second = System.currentTimeMillis() / 1000;
                if (currStayTime >= 300000 && second % 15 == 0) {// 看视频五分钟(300000ms)再弹窗
//                    showDialog();
//                    pause();
//                    iv_play.setVisibility(View.VISIBLE);
//                    iv_play_vv.setVisibility(View.VISIBLE);
//                    iv_pause.setVisibility(View.GONE);
                }
            }
            handler.sendEmptyMessageDelayed(21031051, 1000);
        }
        if (msg.what == 21031351) {// 记录五分钟后不定时弹窗
            handler.removeMessages(21031351);
            currStayTime += 1000;
            handler.sendEmptyMessageDelayed(21031351, 1000);
        }
        if (msg.what == 21031551) {// 跑马灯计时器

            handler.removeMessages(21031551);

            int l = tv_area_code.getLeft();
            int t = tv_area_code.getTop();
            int r = tv_area_code.getRight();
            int b = tv_area_code.getBottom();

            long second = System.currentTimeMillis() / 1000;
            if (second % 22 == 0) {
                tv_area_code.animate().rotation(360).setDuration(2600).setListener(new MyAnimatorListener() {
                    @Override
                    public void onAnimationEnd(Animator animator) {
                        tv_area_code.animate().rotation(0).setDuration(2600).start();
                    }
                }).start();
            } else if (second % 11 == 0) {
                tv_area_code.animate().rotation(-360).setDuration(2600).setListener(new MyAnimatorListener() {
                    @Override
                    public void onAnimationEnd(Animator animator) {
                        tv_area_code.animate().rotation(0).setDuration(2600).start();
                    }
                }).start();
            }

            if (DIRECTION == 1) {
                tv_area_code.layout(l + STEP, t, l + STEP + SizeUtils.dp2px(77), b);
                if (r > containerX) {
                    DIRECTION = 2;
                }
            } else if (DIRECTION == 2) {
                tv_area_code.layout(l, t + STEP, r, t + STEP + SizeUtils.dp2px(32));
                if (b > containerY) {
                    DIRECTION = 3;
                }
            } else if (DIRECTION == 3) {
                tv_area_code.layout(l - STEP, t, l - STEP + SizeUtils.dp2px(77), b);
                if (l < SizeUtils.dp2px(12)) {
                    DIRECTION = 4;
                }
            } else if (DIRECTION == 4) {
                tv_area_code.layout(l, t - STEP, r, t - STEP + SizeUtils.dp2px(32));
                if (t < 0) {
                    DIRECTION = 1;
                }
            }

//            Logg.i("DIRECTION = " + DIRECTION);
//            Logg.i("l,t,r,b = " + l + "," + t + "," + r + "," + b);
//            Logg.i("containerX,containerY = " + containerX + "," + containerY);

            handler.sendEmptyMessageDelayed(21031551, INTERVAL);
        }
    }

    private void setVideoHint(String txt) {
        tv_hint.setText(txt);
    }

    private void showOrHideCtrl(boolean isShow) {
        if (isShow) {
            rl_title.setVisibility(View.VISIBLE);
            rl_control.setVisibility(View.VISIBLE);
        } else {
            rl_title.setVisibility(View.GONE);
            rl_control.setVisibility(View.GONE);
        }
    }

    // 显示控制按钮一段时间后隐藏
    private void showCtrlAndResetTime() {
        showOrHideCtrl(true);
        HIDE_TIME = TIME;
        handler.sendEmptyMessage(2020031051);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != vv_video) {
            vv_video.stopPlayback();
            handler.removeMessages(2019102551);
        }
        handler.removeMessages(21031051);
        handler.removeMessages(21031351);
        handler.removeMessages(21031551);
    }

    private void initWebview(String url) {
        // 开启js支持
        webview.getSettings().setJavaScriptEnabled(true);
        //2、关闭自动适应
        webview.getSettings().setUseWideViewPort(false);
        webview.getSettings().setLoadWithOverviewMode(false);
        // 3、//重写WebViewClient中的onPageFinished方法
        webview.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                //修改图片大小
                int screenWidth = ScreenUtils.getScreenWidth();
//                String width = String.valueOf(screenWidth - SizeUtils.dp2px(50));
//                String width2 = String.valueOf(screenWidth - SizeUtils.dp2px(10));
                String width2 = String.valueOf(SizeUtils.px2dp(screenWidth) - 15);

                String javascript = "javascript:function ResizeImages() {" +
                        "var myimg,oldwidth;" +
                        "var maxwidth = document.body.clientWidth;" +
                        "for(i=0;i <document.images.length;i++){" +
                        "myimg = document.images[i];" +
//                        "myimg.margin = 0;" +
                        "if(myimg.width > " + width2 + "){" +
                        "oldwidth = myimg.width;" +
                        "myimg.width =" + width2 + ";" +
                        "}" +
                        "}" +
                        "}";
                view.loadUrl(javascript);
                view.loadUrl("javascript:ResizeImages();");
            }
        });
        webview.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return true;
            }
        });

        webview.setBackgroundColor(0); // 设置背景色
//        webview.loadUrl(url);
        webview.loadData(CSS_STYLE + url, "text/html;charset=utf-8", null); // 加载定义的代码，并设定编码格式和字符集。
    }

    private AlertDialog alert;// 弹窗
    private View alert_view;

    public void showDialog() {// 弹窗
        alert.show();
        alert.setCancelable(false);
        alert_view = View.inflate(this, R.layout.layout_alert_video_pop_alert, null);
        TextView tv_title = alert_view.findViewById(R.id.tv_title);// 显示课程名称
        tv_title.setText(detail.getCourse_info().getTitle());
        alert_view.findViewById(R.id.tv_1).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alert.dismiss();
                start();
            }
        });
        alert_view.findViewById(R.id.tv_2).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(CourseDetailActivity.this, MainActivity.class);
                intent.putExtra("guid_id", 2);
                startActivity(intent);
            }
        });

        AlertUtil.setAlertCenterStyle(alert.getWindow(), alert_view, this);
    }

    private AlertDialog alert2;// 弹窗
    private View alert_view2;

    public void showDialog2() {// 弹窗
        alert2.show();
        alert_view2 = View.inflate(this, R.layout.layout_alert_course_detail_comment_alert, null);
        et_comment = alert_view2.findViewById(R.id.et_comment);
        tv_send = alert_view2.findViewById(R.id.tv_send);
        View divider0 = alert_view2.findViewById(R.id.divider0);

        tv_send.setOnClickListener(CourseDetailActivity.this);

        RecyclerView rcv_labels = alert_view2.findViewById(R.id.rcv_labels);
        GridLayoutManager manager = new GridLayoutManager(this, 4);
        rcv_labels.setLayoutManager(manager);
        LabeListAdapter2 labelAdapter = new LabeListAdapter2(CourseDetailActivity.this);
        rcv_labels.setAdapter(labelAdapter);
        labelAdapter.setDataList(labelDataList);

        if (isDataEmpty(labelDataList)) {// 标签为空,不显示分割线
            divider0.setVisibility(View.INVISIBLE);
        }

        AlertUtil.setAlertBottomInStyle(alert2.getWindow(), alert_view2, this);
        alert2.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
        alert2.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE
                | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
    }

    private class RecoListAdapter extends ListBaseAdapter<CourseDetail.RecommendInfo> {

        public RecoListAdapter(Context context) {
            super(context);
        }

        @Override
        public int getLayoutId() {
            return R.layout.item_reco_course_list;
        }

        @Override
        public void onBindItemHolder(SuperViewHolder holder, int position) {
            RelativeLayout rl_item = holder.getView(R.id.rl_item);
            TextView tv_num = holder.getView(R.id.tv_num);
            TextView tv_name = holder.getView(R.id.tv_name);
            TextView tv_desc = holder.getView(R.id.tv_desc);

            CourseDetail.RecommendInfo recommendInfo = mDataList.get(position);
            tv_num.setText(position + 1 + "");
            tv_name.setText(recommendInfo.getTitle());
            tv_desc.setText(recommendInfo.getSummary());

            rl_item.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    course_id = recommendInfo.getId();
                    reqCourseDetail();
                    hideProgress();
                    showProgress();
                }
            });
        }
    }

    private class LabeListAdapter extends ListBaseAdapter<LabelData> {

        public LabeListAdapter(Context context) {
            super(context);
        }

        @Override
        public int getLayoutId() {
            return R.layout.item_teacher_info_label;
        }

        @Override
        public void onBindItemHolder(SuperViewHolder holder, final int position) {
            TextView tv_label = holder.getView(R.id.tv_label);
            tv_label.setText(mDataList.get(position).getLabel());
        }
    }

    private class LabeListAdapter2 extends ListBaseAdapter<LabelData> {

        public LabeListAdapter2(Context context) {
            super(context);
        }

        @Override
        public int getLayoutId() {
            return R.layout.item_teacher_info_label;
        }

        @Override
        public void onBindItemHolder(SuperViewHolder holder, final int position) {
            TextView tv_label = holder.getView(R.id.tv_label);
            tv_label.setText(mDataList.get(position).getLabel());

            if (labelDataList.get(position).isSelect) {
                tv_label.setSelected(true);
                tv_label.setTextColor(Color.parseColor("#070C2B"));
            } else {
                tv_label.setSelected(false);
                tv_label.setTextColor(Color.parseColor("#72ECFB"));
            }

            tv_label.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    labelDataList.get(position).setSelect(!labelDataList.get(position).isSelect);
                    notifyDataSetChanged();
                }
            });
        }
    }

    private class LabelData implements Serializable {
        private static final long serialVersionUID = -9125590898642151310L;
        private String label;
        private boolean isSelect;

        public String getLabel() {
            return label;
        }

        public void setLabel(String label) {
            this.label = label;
        }

        public boolean isSelect() {
            return isSelect;
        }

        public void setSelect(boolean select) {
            isSelect = select;
        }
    }
}